const Koa = require('koa');
const router = require('koa-router')();
const cors = require('@koa/cors');
const koaBody = require('koa-body')();
const tencentcloud = require('tencentcloud-sdk-nodejs');
const secretId = 'AKID3pLeFjYHBoKDqDBIwTkk6OPL3Wps5Ae3';
const secretKey = 'KO4WhcHh4FB9l2DFJBvfDLn4A9vRVIgu';
const app = new Koa();
router.post('/confirmEvents', async (ctx, next) => {
  const { t_id } = ctx.request.body;
  const VodClient = tencentcloud.vod.v20180717.Client;
  const models = tencentcloud.vod.v20180717.Models;
  const Credential = tencentcloud.common.Credential;
  const ClientProfile = tencentcloud.common.ClientProfile;
  const HttpProfile = tencentcloud.common.HttpProfile;
  let cred = new Credential(secretId, secretKey);
  let httpProfile = new HttpProfile();
  httpProfile.endpoint = 'vod.tencentcloudapi.com';
  let clientProfile = new ClientProfile();
  clientProfile.httpProfile = httpProfile;
  let client = new VodClient(cred, '', clientProfile);
  function getEvents() {
    return new Promise((resolve, reject) => {
      let req = new models.PullEventsRequest();
      let params = '{}';
      req.from_json_string(params);
      client.PullEvents(req, function(errMsg, response) {
        if (errMsg) {
          reject(errMsg);
        } else {
          resolve(response.to_json_string());
        }
      });
    });
  }
  function confirmEvents(data) {
    return new Promise((resolve, reject) => {
      let req = new models.ConfirmEventsRequest();
      let parse_data = JSON.parse(data);
      //  找到与t_id对应的事件句柄
      let filter_parse_data = parse_data.EventSet.filter(item => {
        return (
          JSON.parse(
            item.FileUploadEvent.MediaBasicInfo.SourceInfo.SourceContext
          ).t_id == t_id
        );
      });
      let param_v = { EventHandles: [] };
      filter_parse_data.map(item => {
        param_v.EventHandles.push(item.EventHandle);
      });
      console.log(param_v);
      let params = JSON.stringify(param_v);
      req.from_json_string(params);
      client.ConfirmEvents(req, function(errMsg, response) {
        if (errMsg) {
          reject(errMsg);
        } else {
          resolve(response.to_json_string());
        }
      });
    });
  }
  await getEvents()
    .then(confirmEvents)
    .then(data => {
      ctx.body = data;
    })
    .catch(data => {
      ctx.body = data;
    });
});

router.post('/getSignature', async (ctx, next) => {
  const { body } = ctx.request;
  var querystring = require('querystring');
  var crypto = require('crypto');

  // 确定 app 的云 API 密钥
  var secret_id = secretId;
  var secret_key = secretKey;

  // 确定签名的当前时间和失效时间
  var current = parseInt(new Date().getTime() / 1000);
  var expired = current + 86400; // 签名有效期：1天

  // 向参数列表填入参数
  var arg_list = {
    secretId: secret_id,
    currentTimeStamp: current,
    expireTime: expired,
    sourceContext: body.sourceContext ? body.sourceContext : '',
    random: Math.round(Math.random() * Math.pow(2, 32)),
    classId: body.classId
  };

  // 计算签名
  var orignal = querystring.stringify(arg_list);
  var orignal_buffer = new Buffer(orignal, 'utf8');

  var hmac = crypto.createHmac('sha1', secret_key);
  var hmac_buffer = hmac.update(orignal_buffer).digest();

  var signature = Buffer.concat([hmac_buffer, orignal_buffer]).toString(
    'base64'
  );
  ctx.body = signature;
});

router.get('/getClass', async ctx => {
  const VodClient = tencentcloud.vod.v20180717.Client;
  const models = tencentcloud.vod.v20180717.Models;

  const Credential = tencentcloud.common.Credential;
  const ClientProfile = tencentcloud.common.ClientProfile;
  const HttpProfile = tencentcloud.common.HttpProfile;

  let cred = new Credential(secretId, secretKey);
  let httpProfile = new HttpProfile();
  httpProfile.endpoint = 'vod.tencentcloudapi.com';
  let clientProfile = new ClientProfile();
  clientProfile.httpProfile = httpProfile;
  let client = new VodClient(cred, '', clientProfile);
  await new Promise((resolve, reject) => {
    let req = new models.DescribeAllClassRequest();
    let params = '{}';
    req.from_json_string(params);

    client.DescribeAllClass(req, function(errMsg, response) {
      if (errMsg) {
        reject(errMsg);
      }
      resolve(response.to_json_string());
    });
  })
    .then(res => {
      ctx.body = res;
    })
    .catch(e => {
      ctx.body = e;
    });
});

router.get('/get', (ctx, next) => {
  const params = ctx.request.query;
  console.log(params);
  ctx.body = {
    ...params
  };
});

router.post('/post', async (ctx, next) => {
  let { body } = ctx.request;
  console.log(body);
  console.log(ctx.request);
  ctx.body = {
    ...body
  };
});
router.prefix('/api');
app.use(async (ctx, next) => {
  let allow_origin;
  if (process.env.NODE_ENV == 'development') {
    allow_origin = 'http://localhost:8080';
  } else {
    allow_origin = 'http://www.huiazir.com';
  }
  // 允许来自所有域名请求
  ctx.set('Access-Control-Allow-Origin', allow_origin);
  // 这样就能只允许 http://localhost:8080 这个域名的请求了
  // ctx.set("Access-Control-Allow-Origin", "http://localhost:8080");

  // 设置所允许的HTTP请求方法
  ctx.set('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, POST');

  // 字段是必需的。它也是一个逗号分隔的字符串，表明服务器支持的所有头信息字段.
  ctx.set(
    'Access-Control-Allow-Headers',
    'x-requested-with, accept, origin, content-type'
  );

  // 服务器收到请求以后，检查了Origin、Access-Control-Request-Method和Access-Control-Request-Headers字段以后，确认允许跨源请求，就可以做出回应。

  // Content-Type表示具体请求中的媒体类型信息
  ctx.set('Content-Type', 'application/json;charset=utf-8');

  // 该字段可选。它的值是一个布尔值，表示是否允许发送Cookie。默认情况下，Cookie不包括在CORS请求之中。
  // 当设置成允许请求携带cookie时，需要保证"Access-Control-Allow-Origin"是服务器有的域名，而不能是"*";
  ctx.set('Access-Control-Allow-Credentials', true);

  // 该字段可选，用来指定本次预检请求的有效期，单位为秒。
  // 当请求方法是PUT或DELETE等特殊方法或者Content-Type字段的类型是application/json时，服务器会提前发送一次请求进行验证
  // 下面的的设置只本次验证的有效时间，即在该时间段内服务端可以不用进行验证
  // ctx.set('Access-Control-Max-Age', 300);

  /*
  CORS请求时，XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段：
      Cache-Control、
      Content-Language、
      Content-Type、
      Expires、
      Last-Modified、
      Pragma。
  */
  // 需要获取其他字段时，使用Access-Control-Expose-Headers，
  // getResponseHeader('myData')可以返回我们所需的值
  //https://www.rails365.net/articles/cors-jin-jie-expose-headers-wu
  // ctx.set('Access-Control-Expose-Headers', 'myData');

  await next();
});

app.use(koaBody);
app.use(cors());
app.use(router.routes()); //作用：启动路由
app.use(router.allowedMethods()); // 作用： 这是官方文档的推荐用法,我们可以看到router.allowedMethods()用在了路由匹配router.routes()之后,所以在当所有路由中间件最后调用.此时根据ctx.status设置response响应头

app.listen(9001, () => {
  console.log('working in 9001');
});
